﻿//扩展format
Date.prototype.format = function (fmt) { //author: meizz   
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日   
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/** 
* 获取下一个月 
* 
* @date 格式为yyyy-mm-dd的日期，如：2014-01-25 
*/
function getNextMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份  
    var month = arr[1]; //获取当前日期的月份  
    var day = arr[2]; //获取当前日期的日  
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中的月的天数  
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }

    var t2 = year2 + '-' + month2 + '-' + '07';
    return new Date(t2);
}

//当前时间
var newDate = new Date();
//用户编号
var userID = 0;
//编码
var isEdit = true;
//用户名
var userName = '';
//账户类型 == 1 为店铺任务管理员
var customUserType = 0;
//默认post请求地址
var post_url = 'WorkOrder.ashx';
//Ajax请求
var postFun = function (_postUrl, _param, _callback) {
    $.ajax({
        type: "post",
        url: _postUrl,
        data: _param,
        dataType: "json",
        success: function (datas) {
            if (_callback) {
                _callback(datas);
            }
        }
    });
}
//扣分ID
var tidId = 0;
//工单序号
var wId = 0;
//工单编号
var wCode = '';
//视图状态
var viewState = '';
//工单状态
var wType = 1;
var _resetModel = 0;
//对象类型1-门店;2-审批者
var wdType = 1;
//店员图片
var shopMangeImgSrc = '../../images/u15278.png';
//管理员图片
var adminImgSrc = '../../images/u15287.png';
//图片查看器-图片数组
var dataList = [];
//设置图片容器
var setImgList = function () {
    var imgItem = $(".img64");
    dataList = [];
    for (var i = 0; i < imgItem.length; i++) {
        dataList.push(imgItem[i].src)
    }
}
//设置图片查看器
var setImgView = function () {
    setImgList();
    var imgItem = $(".img64");
    for (var j = 0; j < imgItem.length; j++) {
        imgItem[j].index = j;
        imgItem[j].addEventListener("click", function (event) {
            var i = this.index;
            var src = event.target.attributes[1].value;
            var options = {
                dataList: dataList,
                currentSrc: src,
                show_remove_btn: false
            };
            ImgView("imgView", options);
        })
    }
}
//店铺编码
var shopCode = '';
//巡检时间
var tif_checkDate = '';
//获取上一个月
function lastMonthDate() {
    var Nowdate = new Date();
    var vYear = Nowdate.getFullYear();
    var vMon = Nowdate.getMonth() + 1;
    var vDay = Nowdate.getDate();
    //每个月的最后一天日期（为了使用月份便于查找，数组第一位设为0）
    var daysInMonth = new Array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (vMon == 1) {
        vYear = Nowdate.getFullYear() - 1;
        vMon = 12;
    } else {
        vMon = vMon - 1;
    }
    //若是闰年，二月最后一天是29号
    if (vYear % 4 == 0 && vYear % 100 != 0 || vYear % 400 == 0) {
        daysInMonth[2] = 29;
    }
    if (daysInMonth[vMon] < vDay) {
        vDay = daysInMonth[vMon];
    }
    if (vDay < 10) {
        vDay = "0" + vDay;
    }
    if (vMon < 10) {
        vMon = "0" + vMon;
    }
    var date = new Date(vYear, vMon, vDay);
    return date;
}
//创建沟通明细
function createWdItem(wd_item) {
    if (wd_item) {
        var wd_html = '<div class="dl-item"><div class="dl-img"><span>';
        if (wd_item.wd_type === 2) {
            wd_html += '<img src="' + adminImgSrc + '" />';
        } else {
            wd_html += '<img src="' + shopMangeImgSrc + '" />';
        }
        var wd_ImgHtml = createImgHtml(wd_item.wd_ImgList)
        wd_html += '</span></div><div class="dl-content"><div class="dl-user"><span><i class="dlu-name">' + wd_item.wd_submitter + '</i>：</span></div>';
        wd_html += '<div class="dlu-msg"><div class="dl-title"><span><i>' + wd_item.wd_context + '</i></span></div>';
        wd_html += '<div class="img-box">' + wd_ImgHtml + '</div>';
        wd_html += '<div class="dl-time"><span><label class="dl-submitter">' + new Date(wd_item.wd_submittime).format('yyyy-MM-dd hh:mm:ss') + '</label></span></div></div></div>';
        if (wd_item.wd_checktype == true) {
            wd_html += '<div class="dl-result"><span class="wd_type">同意</span></div>';
        }
        if (wd_item.wd_checktype == false) {
            wd_html += '<div class="dl-result"><span class="wd_type">驳回</span></div>';
        }
        wd_html += '</div>';
        $('.dialogs-box').append(wd_html);
        setImgView();
    }

}
//清空明细
var emptyDetail = function () {
    var detail = $('.com-detail');
    $(detail).find('.img-box').empty();
    $(detail).find('.ins_checkContext').text('');
    $(detail).find('.tid_remarks').text('');
    $(detail).find('.ins_parentName').text('');
    $('.dialogs-box').empty();
}
//清空提交表单
var emptyForm = function () {
    $('input:radio[name="op_checktype"]').removeAttr('checked');
    $('.wd_context').val('');
    $('.addImgBoxs').empty();
}
//创建问题明细
var createDeatil = function (rstItem) {
    if (rstItem) {
        tidId = rstItem.tid_id;
        wCode = rstItem.w_code;
        wId = rstItem.w_id;
        shopCode = rstItem.ShopCode;
        wType = rstItem.w_type;
        tif_checkDate = new Date(rstItem.tif_checkDate);
        $('#search-Shops').val(rstItem.ShopName);
        $('#search-checkDate').val(tif_checkDate.format('yyyy-MM-dd'));
        //设置com-detail
        if (wType == 2) {
            $('#resetSubmit').removeClass('hide');
            $('#submit').addClass('hide');
        } else if (wType == 3) {
            $('.com-back').addClass('hide');
        } else {
            $('.com-back').removeClass('hide');
        }

        var detail = $('.com-detail');
        $(detail).find('.ins_parentName').text(rstItem.ins_parentName);
        $(detail).find('.ins_checkContext').text(rstItem.ins_checkContext);
        $(detail).find('.tid_points').text(rstItem.tid_points);
        $(detail).find('.tid_remarks').text(rstItem.tid_remarks);
        if (rstItem.TidImgList != null && rstItem.TidImgList.length > 0) {
            var imgListHtml = createImgHtml(rstItem.TidImgList);
            $(detail).find('.img-box').append(imgListHtml);
            setImgView();
        }
        //设置沟通明细
        var wd_list = rstItem.W_Details;
        if (wd_list != null && wd_list.length > 0) {
            for (var i = 0; i < wd_list.length; i++) {
                var wd_item = wd_list[i];
                createWdItem(wd_item);
            }
        }
    }
}
//获取问题明细
function getDetailByTidId() {
    var get_sel_param = { action: 'GetDetailByTidId', tidId: tidId };
    postFun(post_url, get_sel_param, function (rstData) {
        if (rstData.Success) {
            var rstItem = rstData.Data;
            createDeatil(rstItem);
        }
    });
}
//获取问题明细
function getDetailByWid() {
    var get_sel_param = { action: 'getDetailByWid', wId: wId };
    postFun(post_url, get_sel_param, function (rstData) {
        if (rstData.Success) {
            var rstItem = rstData.Data;
            createDeatil(rstItem);
        }
    });
}
//选中问题明细
var selDetail = function (ele, tid_id) {
    layer.closeAll();
    emptyDetail();
    if (tid_id > 0) {
        tidId = tid_id;
        getDetailByTidId();
    }
}
//图片对象
var imgVo = { Url: '', ImageId: '', tf_id: '' };
//创建图片
var createImgHtml = function (imgList) {
    var imgBoxHtml = '';
    if (imgList) {
        for (var i = 0; i < imgList.length; i++) {
            var imgItem = imgList[i];
            imgBoxHtml += '<div class="img"><span><img class="img64 pint-img" src="' + imgItem.Url + '"/><input type="hidden" class="ImageId" value="' + imgItem.ImageId + '" /></span></div>';
        }
    }
    return imgBoxHtml;
}
//获取所有图片
var getImgVoList = function () {
    var addImgBoxs = $('.addImgBoxs');
    var imgBoxList = $(addImgBoxs).find('.ImgBox');
    var imgVoList = [];
    if (imgBoxList.length > 0) {
        for (var i = 0; i < imgBoxList.length; i++) {
            var item = imgBoxList[i];
            var ImageId = $(item).find('.ImageId').val();
            var imgVo = {};
            imgVo.ImageId = ImageId;
            imgVo.tf_id = 0;
            imgVo.Url = '';
            imgVoList.push(imgVo);
        }
    }
    return imgVoList;
}
//根据图片ID删除图片
function removeImg(ImageId, callback) {
    if (ImageId) {
        var del_param = { action: 'DeleteOSS', Id: ImageId }
        postFun('../ImageHandler.ashx', del_param, function (json) {
            if (json.Success) {
                Ext.net.Notification.show({
                    html: '删除图片成功！',
                    title: '操作提示'
                });
            } else {
                Ext.net.Notification.show({
                    html: '删除图片失败，请稍后再试！',
                    title: '操作提示'
                });
            }
            if (callback) {
                callback(json.Success)
            }
        });
    }
}
//删除图片
function btnRemoveImg(ele) {
    var ImgBox = $(ele).parents('.ImgBox');
    var ImageId = $(ImgBox).find('.ImageId').val();
    removeImg(ImageId, function (result) {
        if (result) {
            var imgBoxs = $(ImgBox).parents('.addImgBoxs');
            $(ImgBox).remove();
            var imgBox = $(imgBoxs).find('.ImgBox');
            if (imgBox.length >= 10) {
                $(imgBoxs).parents('td').find('.upload_wwh').hide();
            } else {
                $(imgBoxs).parents('td').find('.upload_wwh').show();
            }

        }
    });
}
//鼠标经过图片
function imgMouseover(ele, type) {
    if (!isEdit) return;
    var btns = $(ele).find('.img-box-btns');
    if (type == 1) {
        btns.removeClass('hide');
    } else {
        btns.addClass('hide');
    }
}
//增加图片--带删除按钮
function addImgItem(data) {
    if (data != null) {
        var addImgBoxs = $('.addImgBoxs');
        var imgBox = $(addImgBoxs).find('.ImgBox');
        //超过三张就隐藏
        if (imgBox.length >= 2) {
            $('.upload_wwh').hide();
        }
        var addHtml = "<div class='ImgBox pint-img' onMouseMove='imgMouseover(this,1)' onMouseOut='imgMouseover(this,2)'>" +
            "<div class='img'><span>" +
            "<img class='img64 pint-img' src= '" + data.Url + "' />" +
            "<input type='hidden' class='ImageId' value='" + data.ImageId + "'/>" +
            "</span>" +
            "<div class='img-box-btns hide'><i class='icon-search close-btn' onClick='btnRemoveImg(this)'></i></div>" +
            "</div ></div>";
        addImgBoxs.append(addHtml);
        setImgView();
    }
}
//保存
function savaFrom(btn, wdContext, checktype) {
    var imgs = getImgVoList();
    var wDetail = { wd_submitter: userName, wd_submittime: '', wd_context: wdContext, wd_type: wdType, wd_checktype: checktype, wd_ImgList: imgs };
    var _savaModel = {
        w_id: wId,
        w_code: wCode,
        tid_id: tidId,
        creator: userID,
        ShopCode: shopCode,
        resetModel: _resetModel,
        w_Detail: wDetail
    }
    var sava_param = { action: 'SavaWorkOrder', savaModel: JSON.stringify(_savaModel) };
    postFun(post_url, sava_param, function (rstData) {
        if (rstData.Success) {
            emptyForm();
            emptyDetail();
            wId = rstData.Data.w_id;
            getDetailByWid();
            $(btn).removeAttr("disabled");
            layer.msg('申诉成功！', { icon: 1, time: 2000 });
        } else {
            $(btn).removeAttr("disabled");
            layer.msg(rstData.Message, { icon: 2, time: 2000 });
        }
    });
}
//加载完成-注册事件
$(function () {
    var lastDate = lastMonthDate();
    var _startDate = new Date(lastDate.getFullYear(), lastDate.getMonth(), 1).format('yyyy-MM-dd');
    userID = $("[name='UserID']").val();
    userName = $("[name='UserName']").val();
    customUserType = parseInt($("[name='CustomUserType']").val());
    wId = parseInt($("[name='WId']").val());
    viewState = $("[name='ViewState']").val();
    var temp_idEdit = $("[name='IsEdit']").val();
    if (temp_idEdit != '') {
        if (temp_idEdit == '1') {
            isEdit = false;
        } else {
            isEdit = true;
        }
    }

    if (userID == '' || userID == null) {
        layer.msg('登陆账号为空不能提交工单！', { icon: 1, time: 2000 });
        $('.com-back').addClass('hide');
        $('.conditions').addClass('hide');
    } else {
        $('.com-back').removeClass('hide');
        $('.conditions').removeClass('hide');
    }
    //startDate 控件初始化
    var data_param = { action: 'GetShopList', shopNames: $("#search-Shops").val(), userID: userID };
    var itemSuggest_shop = new itemSuggest('search-Shops', post_url, 'ShopCode', 'ShopName', data_param);
    itemSuggest_shop.SetBtnHide(false); //隐藏按钮
    itemSuggest_shop.SetMultiWord(false); //关闭多选
    itemSuggest_shop.itemPost();
    //店铺选择事件
    $('#search-Shops').on('onSetSelectValue', function (e, keyword, data) {
        var jsonItem = itemSuggest_shop.getSelectItem();
        if (jsonItem != null) {
            shopCode = jsonItem.ShopCode;
            tif_checkDate = new Date(jsonItem.tif_checkDate);
            $('#search-checkDate').val(tif_checkDate.format('yyyy-MM-dd'));
        }
    });


    $('.upload_wwh').imgUpload({
        path: '../ImageHandler.ashx?action=UploadOSS',
        onSuccess: function (res) {
            if (res.Success) {
                Ext.net.Notification.show({
                    html: '上传图片成功！',
                    title: '操作提示'
                });
                var data = res.Data;
                if (data) {
                    addImgItem(data);
                }
            } else {
                Ext.net.Notification.show({
                    html: res.Message,
                    title: '操作提示'
                });
            }
        },
        onFailure: function (res) {
            Ext.net.Notification.show({
                html: '上传图片失败！',
                title: '操作提示'
            });
        }
    });
    //只有管理员才能设置权限
    if (customUserType == 1) {
        wdType = 2;
        $('.opinion').removeClass('hide');
    } else {
        $('.opinion').addClass('hide');
    }
    if (viewState == "Query" && wId > 0) {
        getDetailByWid();
        if (!isEdit) {
            $('.com-back').addClass('hide');
            $('.conditions').addClass('hide');
        } else {
            $('.com-back').removeClass('hide');
            $('.conditions').removeClass('hide');
        }
    }
    //endDate 控件初始化

    //选择事件
    $('.sel-btn').click(function () {
        //检查是否已经选择店铺
        if (shopCode == '') {
            layer.tips('请选择店铺！', '#search-Shops', { tips: 1 });
            return;
        }
        //检查是否在指定日期内
        var maxCheckDate = getNextMonth(tif_checkDate.format('yyyy-MM-dd'));
        if (newDate > maxCheckDate) {
            layer.tips('已经超过可申诉的时间段(请在7号之前进行申诉)！', '#search-checkDate', { tips: 1 });
            return;
        }
        var get_sel_param = { action: 'GetShopProblemList', shopCode: shopCode, checkDate: tif_checkDate.format('yyyy-MM-dd') };
        postFun(post_url, get_sel_param, function (rstData) {
            $('.sel-Detail table tbody').empty();
            if (rstData.Success) {
                var resList = rstData.Data;
                for (var i = 0; i < resList.length; i++) {
                    var rstItem = resList[i];
                    if (rstItem) {
                        var imgboxHtml = createImgHtml(rstItem.TidImgList);
                        var newRow = '<tr>' +
                            '<td style= "width: 260px; text-align: left;"><i class="ins_checkContext">' + (rstItem.ins_checkContext || '') +
                            '</i>(<i class="points-group"><i class="tid_points">' + (rstItem.tid_points || '') + '</i>分</i>)</td >' +
                            '<td style="width: 260px; text-align: left;"><i class="ins_checkContext">' + (rstItem.tid_remarks || '') + '</i></td>' +
                            '<td style="width: 200px; text-align: left;"><div class="img-box">' + imgboxHtml + '</div></td>' +
                            '<td style="width: 60px; text-align: center; vertical-align: middle">' +
                            '    <button class="btn btn-sel" onclick="selDetail(this,' + rstItem.tid_id + ');">选择</button>' +
                            '</td></tr>';
                        $('.sel-Detail table tbody').append(newRow);
                    }
                }
            }
        });
        //在这里面输入任何合法的js语句
        layer.open({
            type: 1,
            //page层
            area: ['800px', '500px'],
            title: '问题选择',
            shade: 0.6,
            //遮罩透明度
            moveType: 0,
            //拖拽风格，0是默认，1是传统拖动
            shift: 1,
            //0-6的动画形式，-1不开启
            content: $('#problemDetail').html()
        });
    });
    //提交事件
    $('#submit').click(function () {
        var btn = this;
        _resetModel = 0;
        $(btn).attr("disabled", true);
        if (wType > 1) {
            layer.msg('已经结单不能再提交！', { icon: 1, time: 2000 });
            $(btn).removeAttr("disabled");
            return;
        }
        //检查是否在指定日期内
        var maxCheckDate = getNextMonth(tif_checkDate.format('yyyy-MM-dd'));
        if (newDate > maxCheckDate) {
            layer.tips('已经超过可申诉的时间段(请在7号之前进行申诉)！', '#search-checkDate', { tips: 1 });
            $(btn).removeAttr("disabled");
            return;
        }
        //检查意见
        var checktype = NaN;
        if (customUserType == 1) {
            if (wCode == null || wCode == '') {
                layer.msg('管理者不用创建工单！', { icon: 1, time: 2000 });
                $(btn).removeAttr("disabled");
                return;
            }
            var op_checktype = parseInt($('input:radio[name="op_checktype"]:checked').val());
            if (op_checktype != 0 && op_checktype != 1) {
                layer.tips('请选择审批意见！', 'input:radio[name="op_checktype"]');
                $(btn).removeAttr("disabled");
                return;
            } else {
                checktype = op_checktype;
            }
        }

        //检查是否已经选择店铺
        if (shopCode == '') {
            layer.tips('请选择店铺！', '#search-Shops');
            return;
        }
        if (tidId == 0) {
            layer.tips('请选择扣分项！', '.sel-btn');
            return;
        }
        //检查说明
        var wdContext = $.trim($('.wd_context').val());
        if (wdContext == '') {
            layer.tips('请填写说明！', '.wd_context');
            $(btn).removeAttr("disabled");
            return;
        }
        savaFrom(btn, wdContext, checktype);
    });
    //重新申诉
    $('#resetSubmit').click(function () {
        var btn = this;
        _resetModel = 1;
        $(btn).attr("disabled", true);
        if (customUserType == 1) {
            layer.msg('管理者不用填写申诉工单！', { icon: 1, time: 2000 });
            $(btn).removeAttr("disabled");
            return;
        }
        if (wType != 2) {
            layer.msg('只有驳回的工单才可以重新申诉！', { icon: 1, time: 2000 });
            $(btn).removeAttr("disabled");
            return;
        }
        //检查是否在指定日期内
        var maxCheckDate = getNextMonth(tif_checkDate.format('yyyy-MM-dd'));
        if (newDate > maxCheckDate) {
            layer.tips('已经超过可申诉的时间段(请在7号之前进行申诉)！', '#search-checkDate', { tips: 1 });
            $(btn).removeAttr("disabled");
            return;
        }
        //管理者检查 
        var checktype = NaN;
        if (customUserType == 1) {
            //检查意见
            var op_checktype = parseInt($('input:radio[name="op_checktype"]:checked').val());
            if (op_checktype != 0 && op_checktype != 1) {
                layer.tips('请选择审批意见！', 'input:radio[name="op_checktype"]');
                $(btn).removeAttr("disabled");
                return;
            } else {
                checktype = op_checktype;
            }
        }
        //检查是否已经选择店铺
        if (shopCode == '') {
            layer.tips('请选择店铺！', '#search-Shops');
            return;
        }
        if (tidId == 0) {
            layer.tips('请选择扣分项！', '.sel-btn');
            return;
        }
        //检查说明
        var wdContext = $.trim($('.wd_context').val());
        if (wdContext == '') {
            layer.tips('请填写说明！', '.wd_context');
            $(btn).removeAttr("disabled");
            return;
        }
        savaFrom(btn, wdContext, checktype);
    });
});